<template>
  <div @click="initkeyboard">

    <!-- 最上方的操作按钮 -->
    <!-- <Button @click="getData">获取数据</Button> -->
    <div class="button-box">
      <div>
        <Button @click="saveData">保存数据</Button>
      </div>
      <div>
        <Button @click="arrangeDialog">排列</Button>
        <Button v-if="drawLineBoo"
                @click="drawLine">绘制线段</Button>
        <Button v-else
                @click="putLine">提交线段</Button>


        <Button @click="correctHouseFn">矫正房子</Button>
        <Button @click="toggleTheme">背景切换</Button>
        <Button @click="addHouse">添加房子</Button>
        <Button @click="reset">重置地图</Button>
        <Button @click="clear">清除参数</Button>
      </div>
    </div>

    <!-- 右上角控制按钮：这是画布宽高角度的控制按钮 -->
    <div class="draw-map-container container">
      <div class="controls"
           @click.prevent.stop>
        <div style="color: gray">
          <div class="slider-box">
            <div>角度：</div>
            <div class="right">
              <Slider v-model="houseParam.deg"
                      :min="-1"
                      :max="180"
                      @input="initMap"
                      show-input
                      vertical></Slider>
            </div>
          </div>
          <div class="slider-box">
            <div>宽：</div>
            <div class="right">
              <Slider v-model="houseParam.width"
                      :min="0"
                      :max="180"
                      @input="initMap"
                      show-input></Slider>
            </div>
          </div>
          <div class="slider-box">
            <div>高：</div>
            <div class="right">
              <Slider v-model="houseParam.height"
                      :min="0"
                      :max="180"
                      @input="initMap"
                      show-input></Slider>
            </div>
          </div>
          <div class="slider-box">
            共识别到{{ recognitionHouseAll }}个房子
          </div>
        </div>
      </div>

      <!-- 主画布内容：画布标签和背景图标签 -->
      <div class="canvas-box">
        <div class="canvas-bg"
             :style="theme[themeKey].bg">
          <img ref="img"
               :src="img.src"
               alt="背景图"
               v-show="theme[themeKey].imgShow"
               :style="{
              width: `${img.width}px`,
              top: `${img.top}px`,
              left: `${img.left}px`
            }">
        </div>
        <canvas id="draw-map-canvas"
                :class="{ 'drag-canvas': keys.space }"
                width="1000"
                height="1000"
                class="map-canvas"
                ref="map-canvas"
                @click="handleClick"
                @keydown="onkeydown"></canvas>
      </div>

    </div>


    <!-- 排列弹框 -->
    <Modal
        v-model="modalVisiable"
        title="房子列数设置"
        @on-ok="arrangeOk"
        @on-cancel="arrangeCancel">
        请输入列数: <InputNumber :max="20" :min="1" v-model="colValue"></InputNumber>
    </Modal>
  </div>
</template>

<script>
// 1.正常单击选中房子，只有按照ctrl才可以选中多个，如果在ctrl选中了几个，松开ctrl再点单个默认是最后一个 √（ctrl点选加，再次点选减）
// 2.取消选中一样esc直接取消选中 √
// 3.增加框选功能 √（ctrl+鼠标框选）
// 4.按住空格，鼠标变成小手进行拖拽 √
// 5.背景图变成地图图片 √
// 6.增加对选中房子按照某个角度排成一排的功能 √
// 7.修正房子选中计算逻辑 √
// 8.增加道路移动功能 √？
// 9.放大缩小使用鼠标滑轮 √（ctrl+↑滚轮放大，ctrl+↓滚轮缩小）
// 10.全选，反选等按钮最好支持快捷键 √（ctrl-a全选，ctrl-shift-a反选）
// 11.杆路对选中的杆进行直线修正 ？
import {
  getMapData,
  saveMapData,
  correctHouse,
  saveMapLineData,
  setHouseArrange
} from '@/api/app'
import imgSrc from './bg2.jpg'
const isInPolygon = (point, points) => {
  let n = points.length
  let nCross = 0
  for (let i = 0; i < n; i++) {
    let p1 = points[i]
    let p2 = points[(i + 1) % n]
    if (p1.y === p2.y) {
      continue
    }
    if (point.y < Math.min(p1.y, p2.y)) {
      continue
    }
    if (point.y >= Math.max(p1.y, p2.y)) {
      continue
    }
    let x = (point.y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y) + p1.x
    if (x > point.x) {
      nCross++
    }
  }
  return (nCross % 2 === 1)
}
// 初始化常量
const defaultParam = {
  scale: 1, // 缩放比例
  canvasW: 1000, // 画布大小
  canvasH: 1000, // 画布大小
  origin: { x: 500, y: 500 } // 圆点位置
}
// 初始主题：目前是深色和图片为底色两种主题
const theme = {
  dark: {
    bg: 'background-color: black',
    imgShow: false,
    houseColor: '#808695',
    roadColor: '#FFFF00',
    checkedColor: '#2d8cf0',
    lineColor: '#57a3f3'
  },
  img: {
    bg: '',
    imgShow: true,
    houseColor: '#0000FF',
    roadColor: '#FFFF00',
    checkedColor: '#FF0000',
    lineColor: '#57a3f3'
  }
}

export default {
  name: 'DrawMap',
  props: {
    mapId: [Number, String],
    mapTitle: String
  },
  data () {
    return {
      ...defaultParam,
      canvasCtx: '',
      center: {},
      mapDiff: [0, 0],
      dragDiff: [0, 0, false],
      // 数据结构 { poleLineList, poleList, imageData }
      poleLineList: [],
      poleList: [],
      imageData: { house: [] },
      markList: [],
      polygonsList: [],
      // 房子宽高角度
      houseParam: {
        deg: -1,
        width: 0,
        height: 0,
        r: 1
      },
      houseCheckList: [],
      roadsCheckList: {
        cartway: [],
        river: [],
        railway: [],
        highway: []
      },
      sectionRoadCheckList: {
        cartway: {},
        river: {},
        railway: {},
        highway: {}
      },
      poleCheckList: [],
      addCanvasMark: false,
      // 键盘事件
      keys: {
        ctrl: false,
        esc: false,
        space: false,
        alt: false,
        shift: false,
        a: false,
        d: false,
        h: false,
        w: false
      },
      mousepoints: [[0, 0]],
      islocked: {
        poleLine: true,
        roads: false,
        house: false
      },
      img: {
        top: 0,
        left: 0,
        width: 0,
        src: imgSrc
      },
      themeKey: 'dark',
      theme,

      drawLineBoo: true, // 绘制 和 提交数据切换
      pointArr: [], // 单个点
      linePoints: [], // 点击的所有点
      finalRenderArr: [], // 点击 提交数据 最终绘制的双线坐标
      saveLineArr: [], // 保存数据 提交的双线坐标

      drawLineArr: [], // 渲染在画布上的坐标

      modalVisiable: false, //  排列model显示
      colValue: 1, // 排列列数
      checkedHouseArr: [], // 选中的房子
      flagValue: '缩放',
      slefDiff: [0, 0, false],
      recognitionHouseAll: 0, // 识别房子总数
      newHouseArr: [], // 存旧的坐标和新角度
      widthData: '',
      heightData: ''
    }
  },
  computed: {
    // 计算属性里通过主题颜色计算画笔颜色
    houseColor () {
      let key = this.themeKey
      return theme[key].houseColor
    },
    roadColor () {
      let key = this.themeKey
      return theme[key].roadColor
    },
    checkedColor () {
      let key = this.themeKey
      return theme[key].checkedColor
    },
    lineColor () {
      let key = this.themeKey
      return theme[key].lineColor
    }
  },
  async mounted () {
    // 获取焦点
    document.getElementById('draw-map-canvas').focus()
    // 获取数据
    await this.getData()
    // 键盘事件
    this.initkeyboard()
    // 鼠标滚轮事件
    this.initmousewhell()
  },
  watch: {
    // 监听此id来更新数据
    async mapId () {
      await this.getData()
      this.reset()
    },
    // 监听所有键盘事件
    keys: {
      handler (v) {
        if (v.esc) {
          this.houseCheckList = []
          this.checkedHouseArr = []
          this.roadsCheckList = {
            cartway: [],
            river: [],
            railway: [],
            highway: []
          }
          this.poleCheckList = []
          this.initMap()
        } else if (v.ctrl && v.shift && v.a) { // ctrl+shift+a 选中所有房子
          this.checkAllHouse(false)
        } else if (v.ctrl && !v.shift && v.a) { // ctrl+a 选中所有房子
          this.checkAllHouse(true)
        }
      },
      deep: true
    },
    // 监听背景图
    img: {
      handler () { },
      deep: true
    },
    scale: {
      handler (v) {
        if (v) {
          this.flagValue = "缩放"
          this.addLine(this.canvasCtx)
        }
      }
    }
  }, 
  methods: {
    // 接口获取数据
    async getData () {
      // 获取数据
      let res = await getMapData({ id: this.mapId })
      let mapData = res.data.data
      let imgUrl = res.data.imgUrl
      this.img.src = imgUrl || imgSrc

      // 处理数据
      if (mapData) {
        mapData = JSON.parse(mapData)
        this.poleLineList = mapData.poleLineList
        this.poleList = mapData.poleList
        this.imageData = mapData.imageData
        this.polygonsList = mapData.polygonsList
        this.widthData = mapData.width
        this.heightData = mapData.height

        let setHouseAll = new Set(this.imageData.house) 
        this.imageData.house = [...setHouseAll]
        this.newHouseArr = []

        this.imageData.house.map((item, index) => {
          let _obj = JSON.stringify(item),
          objClone = JSON.parse(_obj);
          this.newHouseArr.push({
            oldPoint: objClone,
            deg: -1,
            flag: 0
          })
        })
      }
      // 初始化画布内容
      this.initMap()
      // 初始化鼠标事件
      this.initMousemove()
      // 重置背景图片属性
      this.$nextTick(() => {
        setTimeout(() => {
          const img = {
            width: this.$refs.img.naturalWidth * defaultParam.scale,
            left: 0,
            top: 0
          }
          Object.assign(this.img, img)
        }, 1)
      })
    },
    // 保存数据
    async saveData () {
      if (this.saveLineArr && this.saveLineArr.length != 0) {
        this.imageData.roads[0].cartway = this.saveLineArr
      }

      let house2Arr = []
      this.newHouseArr.map((item, index) => {
        house2Arr.push({
          point: item.oldPoint,
          deg: item.deg
        })
      })
      // this.imageData.house2 = house2Arr

      this.imageData.house.forEach((item, index) => {
        for (let i = 0 ; i < item.length; i ++) {
          item[i] = [parseInt(item[i][0]), parseInt(item[i][1])]
        }
      })
      
      let mapData = {
        poleLineList: this.poleLineList,
        poleList: this.poleList,
        imageData: this.imageData,
        polygonsList: this.polygonsList,
        radioMatrix: '',
        types: ''
      }
      mapData = JSON.stringify(mapData)
      // 接口获取数据
      saveMapData({
        data: mapData,
        id: this.mapId,
        title: this.mapTitle
      }).then(res => {
        if (res.type === 'application/force-download') {
          this.$Message.success('上传成功')
          let blob = new Blob([res])
          let objectUrl = URL.createObjectURL(blob)
          let a = document.createElement('a')
          document.body.appendChild(a)
          a.style = 'display: none'
          a.href = objectUrl
          a.download = new Date().getTime() + '.dxf'
          a.click()
        } else {
          var blobReader = new Response(res).json()
          blobReader.then(msg => {
            this.$Message.error({
              content: msg.message,
              duration: 10
            })
          })
        }
        this.currentFileList = new FormData()
        this.fileList = []
      })
    },

    // 矫正房子
    async correctHouseFn() {
      if (this.saveLineArr && this.saveLineArr.length != 0) {
        this.imageData.roads[0].cartway = this.saveLineArr
      }

      let house2Arr = []
      this.newHouseArr.map((item, index) => {
        house2Arr.push({
          point: item.oldPoint,
          deg: item.deg
        })
      })
      this.imageData.tilthouse = house2Arr

      this.imageData.house.forEach((item, index) => {
        for (let i = 0 ; i < item.length; i ++) {
          item[i] = [parseInt(item[i][0]), parseInt(item[i][1])]
        }
      })

      let mapData = {
        width: this.widthData,
        height: this.heightData,
        poleLineList: this.poleLineList,
        poleList: this.poleList,
        imageData: this.imageData,
        polygonsList: this.polygonsList,
        radioMatrix: '',
        types: ''
      }
      mapData = JSON.stringify(mapData)
      // 接口获取数据
      correctHouse({
        data: mapData,
        id: this.mapId,
        title: this.mapTitle
      }).then(res => {
        if (res.code == 200) {
          // 处理数据
          if (res.data) {
            let mapData = JSON.parse(res.data)
            this.poleLineList = mapData.poleLineList
            this.poleList = mapData.poleList
            this.imageData = mapData.imageData
            this.polygonsList = mapData.polygonsList
            this.widthData = mapData.width
            this.heightData = mapData.height

            let setHouseAll = new Set(this.imageData.house) 
            this.imageData.house = [...setHouseAll]
            this.newHouseArr = []

            this.imageData.house.map((item, index) => {
              let _obj = JSON.stringify(item),
              objClone = JSON.parse(_obj);
              this.newHouseArr.push({
                oldPoint: objClone,
                deg: -1,
                flag: 0
              })
            })
          }
          // 初始化画布内容
          this.initMap()
          // 初始化鼠标事件
          this.initMousemove()
          // 重置背景图片属性
          // this.$nextTick(() => {
          //   setTimeout(() => {
          //     const img = {
          //       width: this.$refs.img.naturalWidth * defaultParam.scale,
          //       left: 0,
          //       top: 0
          //     }
          //     Object.assign(this.img, img)
          //   }, 1)
          // })
        }
      })
    },


    // 缩小画布
    smaller () {
      this.canvasCtx.clearRect(0, 0, 1000, 1000)
      this.scale = this.scale * 0.9
      // 居中缩小
      let diff = ((this.scale / 0.9 - this.scale) * defaultParam.canvasW) / 2
      let [mapX, mapY] = this.mapDiff
      this.mapDiff = [mapX + diff, mapY + diff]
      this.flagValue = "缩放"
      this.initMap()
    },
    // 放大画布
    bigger () {
      this.canvasCtx.clearRect(0, 0, 1000, 1000)
      this.scale = this.scale * 1.1
      // 居中放大
      let diff = ((this.scale - this.scale / 1.1) * defaultParam.canvasW) / 2
      let [mapX, mapY] = this.mapDiff
      this.mapDiff = [mapX - diff, mapY - diff]
      this.initMap()
    },
    // 重置画布
    reset () {
      this.scale = defaultParam.scale
      this.mapDiff = [0, 0]
      this.houseCheckList = []
      this.roadsCheckList = {
        cartway: [],
        river: [],
        railway: [],
        highway: []
      }
      this.poleCheckList = []
      this.pointArr = []
      this.linePoints = []
      this.drawLineArr = []
      this.checkedHouseArr = []
      this.drawLineBoo = true
      this.clear()
      this.getData()
      this.slefDiff = this.dragDiff;
      // 重置背景图片
      const img = {
        width: this.$refs.img.naturalWidth * defaultParam.scale,
        // height: defaultParam.canvasH,
        left: 0,
        top: 0
      }
      Object.assign(this.img, img)
    },
    // 清除画布
    clear () {
      this.houseDeg = -1
      this.houseParam = {
        deg: -1,
        width: 0,
        height: 0,
        r: 1
      }
    },
    // 画布点击事件
    handleClick (e) {
      if (this.keys.ctrl) { // ctrl 添加当前选中房子
        // 选中房子
        this.checkedHouse(e)
        // 选中道路
        // this.checkRoads(e)
        // 选中线段
        this.checkedLine(e)
        // 选中杆
        !this.islocked.poleLine && this.checkedPoleLine(e)
      } else if (this.keys.alt) { // alt 减去当前选中房子
        this.checkedHouse(e, 'pop-checked')
      } else { // 没有键盘事件，只留最后选中的一个房子
        this.checkedHouse(e, 'last-checked')
      }
      this.initMap()
    },

    // 选中某条线段
    checkedLine(e) {
        // 鼠标点击的坐标
        var px = this.jisuan2(e.offsetX, this.scale),
            py = this.jisuan2(e.offsetY, this.scale);
        var lines = []
        this.drawLineArr.forEach((item, index) => {
          lines.push({
            flag:0,
            p1: item[0],
            p2: item[1]
          })
        })

        // 逐条线确定是否有点中
        var offset = 2;                         // 可接受（偏移）范围
        for (var i = 0; i < lines.length; i++) {
            var p1 = lines[i].p1;               // 直线起点
            var p2 = lines[i].p2;               // 直线终点 
            var flag = 0;                       // 1 - 点中
            var minX = Math.min(p1.x, p2.x);    // 较小的X轴坐标值
            var maxX = Math.max(p1.x, p2.x);    // 较大的X轴坐标值
            var minY = Math.min(p1.y, p2.y);    // 较小的Y轴坐标值
            var maxY = Math.max(p1.y, p2.y);    // 较大的Y轴坐标值
 
            if (p1.y === p2.y) {
                // 水平线
                if ((px >= minX && px <= maxX) && (py >= minY - offset && py <= maxY + offset)) {
                    flag = 1;
                    // lines[i].crossPoint = { x: px, y: p1.y };         // 直线上交叉点  
                }
 
            }
            else if (p1.x === p2.x) {
                // 垂直线
                if ((py >= minY && py <= maxY) && (px >= minX - offset && px <= maxX + offset)) {
                    flag = 1;
                    // lines[i].crossPoint = { x: p1.x, y: py };       // 直线上交叉点  
                }
            }
            else {
                // 斜线 (先判断点是否进入可接受大范围(矩形)，然后再根据直线上的交叉点进行小范围比较)
                if ((px >= minX && px <= maxX) && (py >= minY - offset && py <= maxY + offset)) {
                    //求Y轴坐标
                    //方法1：根据tanθ= y/x = y1/x1, 即y = (y1/x1)*x  (该方法有局限性，垂直线(p2.x - p1.x)=0，不能用)
                    //var y = ((p2.y - p1.y) / (p2.x - p1.x)) * (px - p1.x);
 
                    //方法2：先求弧度hudu，根据cosθ=x/r, r=x/cosθ,求得r，再根据sinθ=y/r, y=sinθ*r, 求得y 
                    var hudu = Math.atan2(p2.y - p1.y, p2.x - p1.x);        // 直线的弧度(倾斜度)
                    // 用三角函数计出直线上的交叉点
                    var r = (px - p1.x) / Math.cos(hudu);                   // 直角三角形的斜边（或理解成圆的半径）
                    var y = Math.sin(hudu) * r;                             // Y轴坐标
 
                    var p = { x: px, y: p1.y + y };                         // 直线上的交叉点

                    if ((Math.abs(px - p.x) <= offset) && (Math.abs(py - p.y) <= offset)) {
                        flag = 1;                                           // 1 - 点中
                    }
                    lines[i].crossPoint = p;                                // 直线上的交叉点
                }
            }
            if (flag === 1) {
              if (this.drawLineArr[i].flag == 1) {
                lines[i].flag = 0;
                this.drawLineArr[i].flag = lines[i].flag
              } else {
                lines[i].flag = ((lines[i].flag + 1) % 2);                  // 0、1切换
                this.drawLineArr[i].flag = lines[i].flag
              }
              break;
            }
        }
        this.addLine(this.canvasCtx);
    },
    
    // 按钮: 绘制线段
    drawLine () {
      this.scale = 1
      this.mapDiff = [0, 0]
      this.slefDiff = this.dragDiff
      // 重置背景图片属性
      this.$nextTick(() => {
        setTimeout(() => {
          const img = {
            width: this.$refs.img.naturalWidth * defaultParam.scale,
            left: 0,
            top: 0
          }
          Object.assign(this.img, img)
        }, 1)
      })
      this.initMap()
      this.drawLineBoo = false
    },
    // 按钮: 提交线段
    putLine () {  
      this.finalRenderArr = []
      this.saveLineArr = []

      let allPointArr = []
      this.linePoints.map((item, index) => {
        allPointArr.push({
          start: { x: item[0].x, y: item[0].y, scaleLzx: item[0].scaleLzx },
          end: { x: item[1].x, y: item[1].y, scaleLzx: item[1].scaleLzx }
        })
        return allPointArr
      })

      saveMapLineData(allPointArr).then(res => {
        if (res.code === 200) {
          this.pointArr = []
          let leftArr = []
          let originalArr = []
          let rightArr = []
          let saveLeftArr = []
          let saveRightArr = []
          let result = res.data
          result.forEach((item, index) => {
            leftArr.push([item.leftLine.start, item.leftLine.end])
            originalArr.push([item.originalLine.start, item.originalLine.end])
            rightArr.push([item.rightLine.start, item.rightLine.end])
            saveLeftArr.push([[item.leftLine.start.x, item.leftLine.start.y, item.leftLine.start.scaleLzx], [item.leftLine.end.x, item.leftLine.end.y, item.leftLine.end.scaleLzx]])
            saveRightArr.push([[item.rightLine.start.x, item.rightLine.start.y, item.rightLine.start.scaleLzx], [item.rightLine.end.x, item.rightLine.end.y, item.rightLine.end.scaleLzx]])
          });

          this.finalRenderArr = this.finalRenderArr.concat(leftArr).concat(rightArr)
          let savePoints = []
          savePoints = savePoints.concat(saveLeftArr).concat(saveRightArr)
          
          savePoints.map((item, index) => {
            if (item instanceof Array) {
              item.forEach((pointsItem, pointsIndex) => {
                savePoints[index][pointsIndex] = [parseInt(this.jisuan2(pointsItem[0], pointsItem[2])), parseInt(this.jisuan2(pointsItem[1], pointsItem[2]))]
              })
            } 
          })

          this.saveLineArr = savePoints

          this.drawLineArr = this.finalRenderArr
          this.initMap()
          this.drawLineBoo = true
        }
      })
    },
    // 添加线段
    addLine (ctx) {
        let arr = []
        this.drawLineArr.map((o, index) => {
          if (o.flag && o.flag === 1) {
              arr.push(this.drawLineArr[index])
          }
          if (!(o[0].scaleLzx) || !(o[1].scaleLzx)) {
            o[0].scaleLzx = this.scale
            o[1].scaleLzx = this.scale
          }
          ctx.beginPath();

          //x2,y2就是scale为1的时候的第一个点的坐标
          let x2 = this.jisuan2(o[0].x,o[0].scaleLzx);
          let y2 = this.jisuan2(o[0].y,o[0].scaleLzx);

          let x2tm = x2 + this.dragDiff[0]/this.scale;
          let y2tm = y2 + this.dragDiff[1]/this.scale;

          //x3,y3就是scale为第二个点比例的时候的第一个点的坐标
          let x3 = this.jisuan(x2tm,this.scale);
          let y3 = this.jisuan(y2tm,this.scale);
          

          x3 = x3 + this.slefDiff[0]
          y3 = y3 + this.slefDiff[1]
          
          //x2,y2就是scale为1的时候的第一个点的坐标
          let x4 = this.jisuan2(o[1].x,o[1].scaleLzx);
          let y4 = this.jisuan2(o[1].y,o[1].scaleLzx);

          let x4tm = x4 + this.dragDiff[0]/this.scale;
          let y4tm = y4 + this.dragDiff[1]/this.scale;  
          
          //x3,y3就是scale为第二个点比例的时候的第一个点的坐标
          let x5 = this.jisuan(x4tm,this.scale);
          let y5 = this.jisuan(y4tm,this.scale);

          x5 = x5 + this.slefDiff[0]
          y5 = y5 + this.slefDiff[1]

          ctx.moveTo(x3,y3);
          ctx.lineTo(x5,y5);
          ctx.closePath();
          ctx.strokeStyle = (o.flag && o.flag === 1)? 'blue' : 'rgb(255,75,255)';
          ctx.stroke();
        })
    },
    jisuan(x,scaleLLL) {
      return 500-(500-x)*scaleLLL;
    },
    //从实际坐标推导scale为1的时候的坐标
    jisuan2(x,scaleLLL) {
      return 500-(500-x)/scaleLLL;
    },
     // 滚动
    gundong(ctx){
      this.drawLineArr.map((o, index) => {
        //x2,y2就是scale为1的时候的第一个点的坐标
        let x2 = this.jisuan2(o[0].x,o[0].scaleLzx);
        let y2 = this.jisuan2(o[0].y,o[0].scaleLzx);

        let x3 = this.jisuan2(o[1].x,o[1].scaleLzx);
        let y3 = this.jisuan2(o[1].y,o[1].scaleLzx);

        let x2m = this.jisuan(x2,this.scale);
        let y2m = this.jisuan(y2,this.scale);

        let x3m = this.jisuan(x3,this.scale);
        let y3m = this.jisuan(y3,this.scale);

        ctx.moveTo(x2m, y2m);
        ctx.lineTo(x3m, y3m);
        ctx.closePath();
        ctx.strokeStyle = 'rgb(255,75,255)';
        ctx.stroke();
      })
    },

    // 切换主题
    async toggleTheme () {
      this.themeKey = this.themeKey === 'dark'
        ? 'img' : 'dark'
      this.initMap();
      // 重置背景图片属性
      this.$nextTick(() => {
        setTimeout(() => {
          const img = {
            width: this.$refs.img.naturalWidth * this.scale,
          }
          Object.assign(this.img, img)
        }, 1)
      })
    },
    // 给画布添加一个房子
    addHouse () {
      const height = defaultParam.canvasH
      const scale = defaultParam.scale
      const item = [
        [1, height / scale - 1],
        [50, height / scale - 1],
        [50, height / scale - 50],
        [1, height / scale - 50]
      ]
      this.imageData.house.push(item)
      this.initMap()
    },
    // 在画布内选中一个房子
    checkedHouse (e, type = 'toggle-checked') {
      // 选房子
      let { offsetX, offsetY } = e
      let pointsArr = []
      let points = []
      let index = this.imageData.house.findIndex(list => {
        points = list.map(o => { // [x, y] = o
          const [x, y] = this.setScale(o)
          return { x, y }
        })

        return isInPolygon({ x: offsetX, y: offsetY }, points)
      })

      points.forEach((item, index) => {
        pointsArr.push([item.x, item.y])
      })

      if (index > -1) {
        let curIndex = this.houseCheckList.findIndex(i => i === index)
        if (type === 'toggle-checked') {
          if (curIndex > -1) {
            this.houseCheckList.splice(curIndex, 1)
            this.checkedHouseArr.splice(pointsArr, 1)
            if (!this.houseCheckList.length) {
              this.houseDeg = -1
            }
          } else {
            this.houseCheckList.push(index)
            this.checkedHouseArr.push(pointsArr)
          }
        } else if (type === 'push-checked') {
          if (curIndex === -1) {
            this.checkedHouseArr.push(pointsArr)
            this.houseCheckList.push(index)
          }
        } else if (type === 'last-checked') {
          if (curIndex === -1) {
            this.checkedHouseArr = [pointsArr]
            this.houseCheckList = [index]
          }
        } else if (type === 'pop-checked') {
          if (curIndex > -1) {
            this.houseCheckList.splice(curIndex, 1)
            this.checkedHouseArr.splice(pointsArr, 1)

            if (!this.houseCheckList.length) {
              this.houseDeg = -1
            }
          }
        }

        return true
      }
    },
    // 在画布内选中所有房子
    checkAllHouse (isAll) {
      this.houseParam = {
        deg: -1,
        width: 0,
        height: 0,
        r: 1
      }

      let allListArr = []
      let list = this.imageData.house.map((o, i) => {
        allListArr.push(o)
        return i
      })
     
     if (isAll) {
        this.houseCheckList = list
        this.checkedHouseArr = allListArr

      } else {
        this.houseCheckList = list.filter(o => !this.houseCheckList.includes(o))
        this.checkedHouseArr = list.filter(o => !this.checkedHouseArr.includes(o))
      }
      this.initMap()
    },
    // 在画布内选中若干个房子
    checkSomeHouse () {
      let indexList = []
      let indexhouseList = []
      this.imageData.house.map((list, i) => {
        // 当前房子某个点在框选内
        let hasOnePointIn = list.some(o => { // [x, y] = o
          const [x, y] = this.setScale(o)
          const point = { x, y }
          const points = this.mousepoints.map(([x, y]) => ({ x, y }))
          return isInPolygon(point, points)
        })
        // 当前房子存入数组
        if (hasOnePointIn) {
          indexList.push(i)
          indexhouseList.push(list)
        }
      })
      // 把找到的房子放入houseCheckList
      indexList.map(i => {
        if (!this.houseCheckList.includes(i)) {
          this.houseCheckList.push(i)
        }
      })

      indexhouseList.map(i => {
        if (!this.checkedHouseArr.includes(i)) {
          this.checkedHouseArr.push(i)
        }
      })

    },
    // 在画布内选中某一条路
    checkRoads (e, type = 'toggle-checked') {
      let [{ cartway }, { river }, { railway }, { highway }] = this.imageData
        .roads || [
          { cartway: [] },
          { river: [] },
          { railway: [] },
          { highway: [] }
        ]
      // 选中路段
      let { offsetX, offsetY } = e
      // 找到对应路段的index
      const findIndexFn = list => list.findIndex(list => {
        const points = list.map(o => { // [x, y] = o
          const [x, y] = this.setScale(o)
          return { x, y }
        })
        return isInPolygon({ x: offsetX, y: offsetY }, points)
      })
      // 储存对应路段的index
      const saveIndexFn = (index, keyname = 'cartway') => {
        if (index > -1) {
          let curIndex = this.roadsCheckList[keyname].findIndex(i => i === index)
          if (type === 'toggle-checked') {
            if (curIndex > -1) {
              this.roadsCheckList[keyname].splice(curIndex, 1)
              if (!this.roadsCheckList[keyname].length) {
                this.houseDeg = -1
              }
            } else {
              this.roadsCheckList[keyname].push(index)
            }
          }
        }
      }
      saveIndexFn(findIndexFn(cartway))
      saveIndexFn(findIndexFn(river))
      saveIndexFn(findIndexFn(railway))
      saveIndexFn(findIndexFn(highway))
    },
    checkSectionRoad () { },
    // 在画布内选中杆路
    checkedPoleLine (e, type = 'toggle-checked') {
      // 选中路段
      let { offsetX: e1, offsetY: e2 } = e
      // 找到对应路段的index，鼠标距离路段小于30时默认已点中
      const findIndexFn = list => list.findIndex(list => {
        const minRange = list.some(({ x, y }) => {
          let [a1, a2] = this.setScale([x, y])
          let d = Math.sqrt((e2 - a2) * (e2 - a2) + (e1 - a1) * (e1 - a1))
          return d < 30
        })
        return minRange
      })
      // 储存对应路段的index
      const saveIndexFn = (index) => {
        if (index > -1) {
          let curIndex = this.poleCheckList.findIndex(i => i === index)
          if (type === 'toggle-checked') {
            if (curIndex > -1) {
              this.poleCheckList.splice(curIndex, 1)
              if (!this.poleCheckList.length) {
                this.houseDeg = -1
              }
            } else {
              this.poleCheckList.push(index)
            }
          }
        }
      }
      saveIndexFn(findIndexFn(this.poleLineList))
    },
    // 设置画布缩放比例
    setScale ([x, y]) {
      let scale = this.scale 
      let diff = this.mapDiff 
      let dragDiff = this.dragDiff 

      x = x * scale
      y = y * scale
      // 地图初始偏移量
      x = x + diff[0]
      y = y + diff[1]
      // 鼠标当前偏移量
      if (this.keys.space) {
        x = x + dragDiff[0]
        y = y + dragDiff[1]
      }
      // return [Math.round(x), Math.round(y)]

      return [x, y]

    },
    // 初始化画布内容
    initMap (update = false) {
      let canvas = document.getElementById('draw-map-canvas')
      let ctx = this.canvasCtx ? this.canvasCtx : canvas.getContext('2d')
      if (update) {
        ctx = canvas.getContext('2d')
      }
      ctx.clearRect(0, 0, 1000, 1000) // 清空画布

      // 鼠标框选（ctrl）|| 鼠标拉线（alt）
      if (this.keys.ctrl || this.keys.alt) {
        ctx.strokeStyle = this.checkedColor
        this.drawMouseRegion(ctx, this.mousepoints)
      }
      // 划线:poleLineList[ [{x,y}*4], [{x,y}*4] ]
      ctx.lineWidth = 2
      ctx.strokeStyle = this.lineColor
      this.drawPoleLine(ctx)
      // 画标记:poleLine[{x,y,name,remark}]
      ctx.lineWidth = 1
      ctx.strokeStyle = this.houseColor
      this.drawMark(ctx)
      // 画道路（公路、河流、铁路、高速路）
      ctx.lineWidth = 1
      ctx.strokeStyle = this.roadColor
      this.drawMark(ctx)
      this.drawRoad(ctx)
      this.canvasCtx = ctx
      // 画房子
      ctx.strokeStyle = this.houseColor
      this.drawHouse(ctx, this.houseParam)
      this.addLine(ctx)
    },
    // 操作：鼠标框选范围辅助线
    drawMouseRegion (ctx, rectArray) {
      // 画框选的长方形-ctrl || 画磁吸对齐线-alt
      ctx.save()
      ctx.beginPath()
      rectArray.map(([x, y], i) => {
        if (i === 0) {
          ctx.moveTo(x, y)
        }
        ctx.lineTo(x, y)
      })
      ctx.closePath()
      ctx.stroke()
      ctx.restore()
    },
    // 初始化画布：画杆路
    drawPoleLine (ctx) {
      let scale = this.scale
      this.poleLineList.map((list, index) => {
        let hasChecked = this.poleCheckList.includes(index)
        // 房子选中时，保存数据
        if (hasChecked && !this.keys.space) {
          let [diffX, diffY, isDraging] = this.dragDiff
          // 选中状态的单体保存偏移数据
          if (isDraging) {
            list.map((o, j) => {
              if (!o.x1) {
                o.x1 = o.x
                o.y1 = o.y
              }
              if (j > 0 && j < list.length - 1) {
                o.x = o.x1 + diffX / scale
                o.y = o.y1 + diffY / scale
              }
            })
          } else {
            // 不拖拽时去掉冗余缓存
            list.map(o => {
              delete o.x1
              delete o.y1
            })
          }
        }
        // 杆没有被选中时，画出杆
        if (hasChecked) {
          ctx.lineWidth = 4
          ctx.strokeStyle = this.checkedColor
        } else {
          ctx.lineWidth = 3
          ctx.strokeStyle = this.lineColor
        }
        ctx.beginPath()
        list.map((o, i) => {
          let [x, y] = this.setScale([o.x, o.y])
          if (i === 0) {
            ctx.moveTo(x, y)
          }
          ctx.lineTo(x, y)
        })
        ctx.stroke()
      })
      // ctx.stroke()
    },
    // 初始化画布：画标记
    drawMark (ctx) {
      let scale = this.scale
      // let poleList = [{
      //   'name': '未命名地标',
      //   'remark': '（1新增',
      //   'styleUrl': '#msn_W',
      //   'x': 571,
      //   'y': 436
      // }]
      this.poleList.map(o => {
        // 画圆
        ctx.beginPath()
        let [x, y] = this.setScale([o.x, o.y])
        let r = parseInt(5 * scale)
        let sAngle = 0
        let eAngle = 2 * Math.PI
        ctx.arc(x, y, r, sAngle, eAngle)
        ctx.stroke()
      })
    },
    // 初始化画布：画路
    drawRoad (ctx) {
      let scale = this.scale
      let [{ cartway }, { river }, { railway }, { highway }] = this.imageData
        .roads || [
          { cartway: [] },
          { river: [] },
          { railway: [] },
          { highway: [] }
        ]

      let fn = (list, keyname = 'cartway') => list.map((list, i) => {
        const hasChecked = this.roadsCheckList[keyname].includes(i)
        // 房子选中时，保存数据
        if (hasChecked && !this.keys.space) {
          let [diffX, diffY, isDraging] = this.dragDiff
          // 选中状态的单体保存偏移数据
          if (isDraging) {
            list.map(o => {
              if (!o[2]) {
                o[2] = o[0]
                o[3] = o[1]
              }
              o[0] = o[2] + diffX / scale
              o[1] = o[3] + diffY / scale
            })
          } else {
            // 不拖拽时去掉冗余缓存
            list.map(o => o.splice(2))
          }
        }
        // 房子没有被选中时，画出房子
        if (hasChecked) {
          ctx.lineWidth = 2
          ctx.strokeStyle = this.checkedColor
        } else {
          ctx.lineWidth = 1
          ctx.strokeStyle = this.roadColor
        }
        ctx.beginPath()
        list.map((o, i) => {
          let [x, y] = this.setScale(o)
          if (i === 0) {
            ctx.moveTo(x, y)
          }
          ctx.lineTo(x, y)
        })
        ctx.closePath()
        ctx.stroke()
      })
      fn(cartway)
      fn(river)
      fn(railway)
      fn(highway)
    },
    // 初始化画布：画房子
    drawHouse (ctx, param) {
      let scale = this.scale
      let alignAngle = null

      
      
      // alt时align对齐角度
      if (this.keys.alt && this.mousepoints.length === 2) {
        const [[a1, a2], [b1, b2]] = this.mousepoints
        alignAngle = Math.atan((b2 - a2) / (b1 - a1))
      }
      // 选中状态的单体旋转方法
      const rotateFn = (list, deg, centerFn = c => c) => {
        let [[a1, a2], [b1, b2], [c1, c2]] = list
        let w = Math.sqrt((b2 - a2) * (b2 - a2) + (b1 - a1) * (b1 - a1))
        let h = Math.sqrt((c2 - b2) * (c2 - b2) + (c1 - b1) * (c1 - b1))
        if (w < h && !(param.width > 0 && param.height > 0)) {
          ;[w, h] = [h, w]
        }
        let alpha = Math.atan(h / 2 / (w / 2))
        let r = Math.sqrt(w * w + h * h) / 2
        let aOffsetCenterX = r * Math.sin(alpha - deg)
        let aOffsetCenterY = r * Math.cos(alpha - deg)
        let bOffsetCenterX = r * Math.sin(deg + alpha)
        let bOffsetCenterY = r * Math.cos(deg + alpha)
        let [centerX, centerY] = centerFn([(c1 + a1) / 2, (c2 + a2) / 2])
        list[0] = [centerX + aOffsetCenterX, centerY + aOffsetCenterY]
        list[1] = [centerX - bOffsetCenterX, centerY + bOffsetCenterY]
        list[2] = [centerX - aOffsetCenterX, centerY - aOffsetCenterY]
        list[3] = [centerX + bOffsetCenterX, centerY - bOffsetCenterY]
        return list
      }

      let setHouseAll = new Set(this.imageData.house)
      this.imageData.house = [...setHouseAll]
      this.recognitionHouseAll = this.imageData.house.length

      

      this.imageData.house.map((list, index) => {
        let hasChecked = this.houseCheckList.includes(index)

        // 房子选中时，保存数据
        if (hasChecked && !this.keys.space) {
          let [diffX, diffY, isDraging] = this.dragDiff
          // 选中状态的单体保存偏移数据
          if (isDraging) {
            list.map(o => {
              if (!o[2]) {
                o[2] = o[0]
                o[3] = o[1]
              }
              o[0] = o[2] + diffX / scale
              o[1] = o[3] + diffY / scale
            })
            // 选中状态的单体保存旋转数据
          } else {
            let deg = 0
            // 选中状态的单体保存宽高数据
            if (param.width > 0 && param.height > 0) {
              let { width: h, height: w } = param
              let [a1, a2] = list[0]
              let [c1, c2] = list[2]
              let [centerX, centerY] = [(c1 + a1) / 2, (c2 + a2) / 2]
              list[0] = [centerX + w / 2, centerY + h / 2]
              list[1] = [centerX - w / 2, centerY + h / 2]
              list[2] = [centerX - w / 2, centerY - h / 2]
              list[3] = [centerX + w / 2, centerY - h / 2]
              // deg = Math.atan((b2 - a2) / Math.abs(b1 - a1))
            }
            // 选中状态的单体保存旋转数据
            if (param.deg > -1) {
              deg = (param.deg * Math.PI) / 180
              rotateFn(list, deg)
              this.newHouseArr[index].deg = param.deg
              this.newHouseArr[index].flag = 1
            }
            // 不拖拽时去掉冗余缓存
            list.map(o => o.splice(2))
          }
          // 选中状态的单体对齐方式
          if (alignAngle !== null) {
            // mapDiff
            const [[e1, e2], [f1, f2]] = this.mousepoints
              // .map(l => l.map(o => o / scale))
              .map(l => {
                let [dx, dy] = this.mapDiff
                return [(l[0] - dx) / scale, (l[1] - dy) / scale]
              })
            const mouseDiff = point => {
              let [a1, a2] = point
              let [x, y] = [0, 0]
              if (e1 !== f1 && e2 !== f2) {
                let kmouse = (f2 - e2) / (f1 - e1)
                let khouse = -(f1 - e1) / (f2 - e2)
                x = (a2 - khouse * a1 + kmouse * e1 - e2) / (kmouse - khouse)
                y = kmouse * x - kmouse * e1 + e2
                return [x - a1, y - a2]
              }
              return [x, y]
            }
            let [[a1, a2], [b1, b2], [c1, c2], [d1, d2]] = list
            const [df1, df2] = mouseDiff([a1, a2])
            list[0] = [a1 + df1, a2 + df2]
            list[1] = [b1 + df1, b2 + df2]
            list[2] = [c1 + df1, c2 + df2]
            list[3] = [d1 + df1, d2 + df2]
          }
        }
        // 房子没有被选中时，画出房子
        let [[a1, a2], [b1, b2], [c1, c2]] = list
        let w = Math.sqrt((b2 - a2) * (b2 - a2) + (b1 - a1) * (b1 - a1))
        let h = Math.sqrt((c2 - b2) * (c2 - b2) + (c1 - b1) * (c1 - b1))
        let [centerX, centerY] = [(c1 + a1) / 2, (c2 + a2) / 2]
        let [oX, oY] = this.setScale([centerX, centerY])

        ctx.save()
        ctx.translate(oX, oY)
        if (hasChecked) {
          ctx.lineWidth = 2
          ctx.strokeStyle = this.checkedColor
        } else {
          ctx.lineWidth = 1
          ctx.strokeStyle = this.houseColor
        }
        ctx.rotate(Math.atan((b2 - a2) / (b1 - a1)))
        ctx.beginPath()
        ctx.rect((-w * scale) / 2, (-h * scale) / 2, w * scale, h * scale)
        ctx.stroke()
        ctx.restore()
      })
    },
    // 初始化鼠标事件
    initMousemove () {
      let $canvas = this.$refs['map-canvas']
      $canvas.onmousedown = e => {
        // ctrl时框选房子（处理houseCheckList数据）
        if (this.keys.ctrl) {
          let prePole = [e.offsetX, e.offsetY]
          $canvas.onmousemove = e => {
            let [preX, preY] = prePole
            let [x2, y2] = [e.offsetX, e.offsetY]
            this.mousepoints = [ // 框选的长方形
              [preX, preY],
              [x2, preY],
              [x2, y2],
              [preX, y2]
            ]
            this.initMap() // 画出长方形 initMap[drawMouseRegion]
          }
          $canvas.onmouseup = e => {
            this.checkSomeHouse() // 框选房子
            this.mousepoints = [[0, 0]] // 框选的长方形归零
            this.initMap() // 画布重绘长方形为点
            $canvas.onmousemove = $canvas.onmouseup = null
          }
          return
        }

        // alt时划线对齐房子
        if (this.keys.alt && this.houseCheckList.length) {
          let prePole = [e.offsetX, e.offsetY]
          $canvas.onmousemove = e => {
            let [preX, preY] = prePole
            let [x2, y2] = [e.offsetX, e.offsetY]
            this.mousepoints = [[preX, preY], [x2, y2]]
            this.initMap()
          }
          $canvas.onmouseup = e => {
            this.mousepoints = [[0, 0]] // 框选或者拉线归零
            this.initMap()
            $canvas.onmousemove = $canvas.onmouseup = null
          }
          return
        }

        // 空格时拖拽画布
        if (this.keys.space) {
          let prePole = [e.offsetX, e.offsetY] // 记录鼠标起始坐标
          let preImgPole = [this.img.left, this.img.top] // 记录背景图起始坐标
          $canvas.onmousemove = e => {
            let [preX, preY] = prePole // 根据鼠标起始坐标，计算当前鼠标偏移量
            this.dragDiff = [e.offsetX - preX, e.offsetY - preY, true]
            // 背景图偏移量
            let [left, top] = preImgPole
            this.img.left = left + e.offsetX - preX
            this.img.top = top + e.offsetY - preY
            this.flagValue = "拖拽"
            if (!this.keys.space) {
              // 拖拽中空格抬起
              $canvas.onmouseup(e)
            }
            this.initMap()
          }
          $canvas.onmouseup = e => {
            let [slefDx, slefDy, slefBoo] = this.slefDiff
            let [dragDx, dragDy, dragBoo] = this.dragDiff

            this.slefDiff[0] = slefDx + dragDx
            this.slefDiff[1] = slefDy + dragDy
            this.slefDiff[2] = dragBoo

            this.dragDiff = [0, 0, false] // 清空鼠标偏移量
            // 记录本次鼠标抬起后，更新画布偏移量
            let [preX, preY] = prePole // 鼠标起始坐标
            let [mapDiffX, mapDiffY] = this.mapDiff // 画布已偏移量
            this.mapDiff = [
              mapDiffX + e.offsetX - preX,
              mapDiffY + e.offsetY - preY
            ] // 画布偏移量

            this.initMap()
            $canvas.onmousemove = $canvas.onmouseup = null
          }
          return
        }

        const hasCheckedSomes = this.houseCheckList.length ||
          this.roadsCheckList.cartway.length ||
          this.roadsCheckList.river.length ||
          this.roadsCheckList.railway.length ||
          this.roadsCheckList.highway.length ||
          this.poleCheckList.length
        // 有房子选中时拖拽房子（计算房子偏移量）
        if (hasCheckedSomes) {
          let prePole = [e.offsetX, e.offsetY] // 记录鼠标起始坐标
          let preImgPole = [this.img.left, this.img.top] // 记录背景图起始坐标
          $canvas.onmousemove = e => {
            let [preX, preY] = prePole // 根据鼠标起始坐标，计算当前鼠标偏移量
            this.dragDiff = [e.offsetX - preX, e.offsetY - preY, true]
            // 背景图偏移量
            let [left, top] = preImgPole
            if (this.keys.space) {
              this.img.left = left + e.offsetX - preX
              this.img.top = top + e.offsetY - preY
            }
            this.initMap()
          }
          $canvas.onmouseup = e => {
            this.dragDiff = [0, 0, false] // 清空鼠标偏移量
            // 记录本次鼠标抬起后，更新画布偏移量
            let [preX, preY] = prePole // 鼠标起始坐标
            let [mapDiffX, mapDiffY] = this.mapDiff // 画布已偏移量
            if (this.keys.space) {
              this.mapDiff = [
                mapDiffX + e.offsetX - preX,
                mapDiffY + e.offsetY - preY
              ] // 画布偏移量
            }
            this.initMap()
            $canvas.onmousemove = $canvas.onmouseup = null
          }
        }

        if (!this.drawLineBoo) {
          let x = e.offsetX; // 鼠标落下时的X
          let y = e.offsetY; // 鼠标落下时的Y
          let scaleLzx = this.scale;
          
          if (this.pointArr.length >= 2) {
            this.pointArr = []
            this.pointArr.push({ x, y ,scaleLzx})
          } else {
            this.pointArr.push({ x, y ,scaleLzx})
          }

          if (this.pointArr.length === 2) {
            this.linePoints.push(this.pointArr)
          }
          this.drawLineArr = this.linePoints

          this.initMap()
        }
      }
    },
    // 键盘事件
    initkeyboard () {
      document.onkeydown = (event) => {
        this.onkeydown(event)
        return false
      }
      // document.addEventListener('onkeydown', (event) => {
      //   this.onkeydown(event)
      //   return false
      // })
      document.onkeyup = (event) => {
        this.onkeyup(event)
      }
      // document.addEventListener('onkeyup', (event) => {
      //   this.onkeyup(event)
      // })
    },
    // 按下时设置某个键盘值
    onkeydown (e) {
      this.setKeysValue(e, true)
    },
    // 抬起时设置某个键盘值
    onkeyup (e) {
      this.setKeysValue(e, false)
    },
    // 设置某个键盘值
    setKeysValue (e, value) {
      if (e.keyCode === 17) {
        this.keys.ctrl = value
      } else if (e.keyCode === 27) {
        this.keys.esc = value
      } else if (e.keyCode === 32) {
        if (this.drawLineBoo == false) {
          e.returnValue = false
          return
        }
        this.keys.space = value
      } else if (e.keyCode === 18) {
        this.keys.alt = value
      } else if (e.keyCode === 16) {
        this.keys.shift = value
      } else if (e.keyCode === 65) {
        this.keys.a = value
      } else if (e.keyCode === 68) {
        this.keys.d = value
      } else if (e.keyCode === 72) {
        this.keys.h = value
      } else if (e.keyCode === 87) {
        this.keys.w = value
      }
    },
    // 鼠标滚轮事件
    initmousewhell () {
      const foo = e => {
        e = e || window.event
        const hasKeys = this.keys.ctrl ||
          this.keys.d ||
          this.keys.w ||
          this.keys.h
        if (hasKeys) {
          e.preventDefault && e.preventDefault()
        } else {
          return false
        }
        if (e.wheelDelta) {
          // 判断浏览器IE，谷歌滑轮事件
          e.wheelDelta > 0 && this.mousewheelup(e)
          e.wheelDelta < 0 && this.mousewheeldown(e)
        } else if (e.detail) {
          e.detail > 0 && this.mousewheeldown(e)
          e.detail < 0 && this.mousewheelup(e)
        }
        return false
      }
      // Firefox
      if (document.addEventListener) {
        document.addEventListener('DOMMouseScroll', foo, false)
      }
      // ie 谷歌
      window.addEventListener('mousewheel', foo, {
        passive: false
      })
    },
    // 向上鼠标滚轮事件
    mousewheelup () {
      if (this.keys.ctrl) {
        this.bigger()
        this.img.width = this.img.width * 1.1
        this.img.height = this.img.height * 1.1
        let diff = ((this.scale - this.scale / 1.1) * defaultParam.canvasW) / 2
        this.img.top = this.img.top - diff
        this.img.left = this.img.left - diff
      } else if (this.keys.d) {
        this.houseParam.deg++
      } else if (this.keys.w) {
        this.houseParam.width++
      } else if (this.keys.h) {
        this.houseParam.height++
      }
    },
    // 向下鼠标滚轮事件
    mousewheeldown () {
      if (this.keys.ctrl) {
        this.smaller()
        this.img.width = this.img.width * 0.9
        this.img.height = this.img.height * 0.9
        let diff = ((this.scale / 0.9 - this.scale) * defaultParam.canvasW) / 2
        this.img.top = this.img.top + diff
        this.img.left = this.img.left + diff
      } else if (this.keys.d) {
        this.houseParam.deg--
      } else if (this.keys.w) {
        this.houseParam.width--
      } else if (this.keys.h) {
        this.houseParam.height--
      }
    },

    // Function: 打开
    arrangeDialog() {
      this.modalVisiable = true
    },
    // Function: 确认排列
    arrangeOk() {
      let params = {
        houseList: this.checkedHouseArr,
        number: this.colValue 
      }
      this.imageData.house = this.imageData.house.filter(item => {
        let idList= this.checkedHouseArr.map(v => v)
        return !idList.includes(item)
      })
      setHouseArrange(params).then((res) => {
        if (res.code == 200) {
          this.imageData.house.push(...res.data)

          this.houseCheckList = []
          this.initMap()
          this.colValue = 1
          this.checkedHouseArr = []
        }
      })
    },

    // Function: 取消排列
    arrangeCancel() {
      this.modalVisiable = false
    }
  }
}
</script>

<style lang="css" scoped>
.container {
  position: relative;
  width: 1000px;
}
::selection {
  background: transparent;
  color: black;
}
.canvas-box {
  background-color: white;
  border: 1px solid silver;
  position: relative;
}
.canvas-box .canvas-bg {
  position: absolute;
  width: 100%;
  height: 100%;
  transform: rotateX(180deg);
  overflow: hidden;
}
.canvas-box .canvas-bg img {
  position: absolute;
  display: block;
  opacity: 0.7;
  /* width: 100%;
  top: 0;
  left: 0; */
  transform: rotateX(180deg);
}
.canvas-box canvas {
  display: block;
  position: relative;
  transform: rotateX(180deg);
}
.controls {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 2;
  min-width: 220px;
}
.controls button {
  margin-bottom: 20px;
}
.controls button + button {
  margin-left: 8px;
}
.drag-canvas {
  cursor: grab;
}
</style>
<style lang="css">
.slider-box {
  display: flex;
  justify-content: space-between;
  white-space: nowrap;
  align-items: center;
}
.button-box {
  width: 1000px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}
.slider-box .right {
  width: calc(100% - 48px);
}
.draw-map-container .controls .ivu-slider-input .ivu-slider-wrap {
  width: 63%;
  margin-right: 100px;
}
.draw-map-container .controls .ivu-slider-input .ivu-input-number {
  float: right;
  width: 61px;
}
</style>
